package cn.com.zj.rpc.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * @ClassName MyRpcClientHandler
 * @Description 自定义Rpc客户端业务处理类
 * 业务：
 * 1.向服务端发送消息
 * 2.接收服务端返回的消息
 * @Author ZikZ227412
 * @DATE 2021/12/9 15:24
 * @Version 1.0
 */
public class MyRpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    private ChannelHandlerContext channelHandlerContext;

    private String requestMessage;

    private String responseMessage;

    public void setRequestMessage(String requestMessage) {
        this.requestMessage = requestMessage;
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        responseMessage = s;
        //唤醒等待线程
        notify();
    }

    /**
     * 连接就绪事件
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelHandlerContext = ctx;
    }

    @Override
    public synchronized Object call() throws Exception {
        //发送消息
        channelHandlerContext.writeAndFlush(requestMessage);
        //线程等待
        wait();
        return responseMessage;
    }


}
